<?php
use Illuminate\Database\Capsule\Manager as DB;

#[默认控制器]
class IndexController extends CommonController
{
    protected $authExcept = ['index', 'init', 'weixinInfo', 'richtext', 'custom', 'asyncPages', 'template', 'upload'];

    public function indexAction()
    {
        redirect('/h5');
        json(['code' => 1, 'msg' => 'welcome']);
    }

    // 初始化商城数据
    public function initAction()
    {
        $platform = getHeader('platform'); // 获取平台标识
        if (!in_array($platform, ['H5', 'App', 'wxMiniProgram', 'wxOfficialAccount'])) {
            throw new Exception('请使用正确客户端访问');
        }

        $data = \app\service\config::get('', $platform);

        json(['code' => 1, 'msg' => '初始化数据', 'data' => $data]);
    }

    public function weixinInfoAction()
    {
        json(['code' => 1, 'msg' => '微信公众号', 'data' => \app\service\config::get('wechat')]);
    }

    public function richtextAction()
    {
        $id = $this->get('id');
        json(['code' => 1, 'msg' => '富文本', 'data' => pagesModel::find($id)]);
    }

    public function customAction()
    {
        $custom_id = $this->get('custom_id');
        $decorate = decorateModel::find($custom_id);
        if (!$decorate) {
            throw new Exception('未找到自定义页面');
        }
        $decorate->template = decorateModel::getCustomDecorate($custom_id);
        json(['code' => 1, 'msg' => '自定义模板数据', 'data' => $decorate]);
    }

    // 同步前端所有页面链接
    public function asyncPagesAction()
    {
        json(['code' => 1, 'msg' => 'ok']);
    }

    // 商城模板数据
    public function templateAction()
    {
        $get = $this->get();
        $platform = getallheaders()['Platform'];
        if (isset($get['shop_id']) && $get['shop_id'] != 0) {
            $template = decorateModel::getCurrentPlatformDecorate('preview', $get['shop_id']);
        } else {
            $template = decorateModel::getCurrentPlatformDecorate($platform);
        }
        json(['code' => 1, 'msg' => '模板数据', 'data' => $template]);
    }

    // 上传
    public function uploadAction()
    {
        $file = $this->getFiles('file');
        json(['code' => 1, 'msg' => '', 'data' => \app\service\cdn::upload($file)]);
    }

    public function expressAction()
    {
        $data = DB::table('express')->select(['name', 'code'])->orderBy('weigh', 'desc')->get();
        json(['code' => 1, 'msg' => '', 'data' => $data]);
    }
}
